package com.LeeCode;

import java.util.ArrayList;
import java.util.List;

/**
 * 复原 IP 地址
 */

public class Code093 {
    public static void main(String[] args) {
        String s = "25525511135";
        System.out.println(new Code093().restoreIpAddresses(s));
    }

    public List<String> restoreIpAddresses(String s) {
        List<String> ans = new ArrayList<>();
        if (s == null || s.length() < 4 || s.length() > 12) return ans;
        backtrace(s, 0, new ArrayList<>(), ans);
        return ans;
    }

    private void backtrace(String s, int index, List<String> path, List<String> ans) {
        if (path.size() == 4) {
            if (index == s.length()) {
                ans.add(String.join(".", path));
            }
            return;
        }

        for (int len = 1; len <= 3; len++) {
            if (index + len > s.length()) break;

            String num = s.substring(index, index + len);
            if (len > 1 && num.charAt(0) == '0') break;
            int digit = Integer.parseInt(num);
            if (0 <= digit && digit <= 255) {
                path.add(num);
                backtrace(s, index + len, path, ans);
                path.remove(path.size() - 1);
            }
        }
    }
}
